package ch.ffhs.radarpp.managers;

import java.io.ByteArrayOutputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import ch.ffhs.radarpp.R;
import ch.ffhs.radarpp.web.WebClient;
import ch.ffhs.radarpp.web.WebManager;
/**
 * 
 * @author Beda
 *
 */
public class ProfilePictureDataManager extends SQLiteOpenHelper implements WebClient {

	private Context context;

	public ProfilePictureDataManager(Context context) {
		super(context, "radarpp", null, 1);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		String userTable = context.getString(R.string.profilepicture_sqlitedatabase);

		db.execSQL(userTable);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public Bitmap getUserBitmap(int userid, Resources res) {
		try {

			SQLiteDatabase database = getReadableDatabase();
			Cursor c = database.query(context.getString(R.string.profilepicture_table_user), new String[] { context.getString(R.string.profilepicture_column_picture) },
					context.getString(R.string.profilepicture_where_userid) + userid, null, null, null, null);

			if (c.moveToFirst()) {
				return getBitmapFromJson(c.getString(0), res);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Bitmap getBitmapFromJson(String value, Resources res) {

		if (value.equalsIgnoreCase("null")) {
			return BitmapFactory.decodeResource(res, R.drawable.ic_dummy);
		} else {
			byte[] decodedString = Base64.decode(value, Base64.DEFAULT);
			Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
			return decodedByte;
		}
	}

	public static String getJsonFromBitmap(Bitmap bitmap) {
		try {
			final int COMPRESSION_QUALITY = 75;
			String encodedImage;
			ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();

			if (bitmap.getWidth() > 300) {

				bitmap = Bitmap.createScaledBitmap(bitmap, 300, bitmap.getHeight() / (bitmap.getWidth() / 300), false);
			}
			
			bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, byteArrayBitmapStream);
			byte[] b = byteArrayBitmapStream.toByteArray();
			encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
			return encodedImage;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public void mergeWithServer() {

		// getWritableDatabase().delete("user", null, null);

		try {
			JSONObject base = new JSONObject();
			base.put(context.getString(R.string.profilepicture_fetch_post_username), PersistentDataManager.getLoginInfo(null).getUsername());
			base.put(context.getString(R.string.profilepicture_fetch_post_password), PersistentDataManager.getLoginInfo(null).getPassword());

			JSONArray array = new JSONArray();

			Cursor c = getReadableDatabase().query(context.getString(R.string.profilepicture_table_user),
					new String[] { context.getString(R.string.profilepicture_column_userid), context.getString(R.string.profilepicture_column_lastupdate) }, null, null, null, null, null);

			while (c.moveToNext()) {
				JSONObject userObject = new JSONObject();
				userObject.put(context.getString(R.string.profilepicture_fetch_post_userid), c.getInt(0));
				userObject.put(context.getString(R.string.profilepicture_fetch_post_lastupdate), c.getString(1));

				array.put(userObject);
			}

			base.put(context.getString(R.string.profilepicture_fetch_post_items), array);

			Log.d("lsdf", base.toString());

			WebManager webManager = new WebManager(this, PersistentDataManager.getAppSettings(this.context));
			webManager.executeHTTPPostRequest(context.getString(R.string.service_mergeprofilepictures), base.toString(), null);

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void requestCompleted(String result, Object context) {

		Log.d("profilepicmerge", result);

		try {

			SQLiteDatabase database = getWritableDatabase();

			JSONArray a = new JSONArray(result);

			for (int i = 0; i < a.length(); i++) {
				JSONObject o = a.getJSONObject(i);

				int userId = o.getInt(this.context.getString(R.string.profilepicture_fetch_post_userid));

				String pic = o.getString(this.context.getString(R.string.profilepicture_fetch_post_pic));
				String lastUpdate = o.getString(this.context.getString(R.string.profilepicture_fetch_post_lastupdate));

				updateOrInsertData(database, pic, lastUpdate, userId);
			}

		} catch (JSONException ex) {
			ex.printStackTrace();
		}
	}

	private void updateOrInsertData(SQLiteDatabase database, String pic, String lastUpdate, int userId) {
		ContentValues vals = new ContentValues();
		vals.put(context.getString(R.string.profilepicture_column_picture), pic);
		vals.put(context.getString(R.string.profilepicture_column_lastupdate), lastUpdate);
		vals.put(context.getString(R.string.profilepicture_column_userid), userId);

		Cursor c = database.query(context.getString(R.string.profilepicture_table_user), new String[] { "count(*)" }, context.getString(R.string.profilepicture_where_userid) + userId, null, null,
				null, null);
		c.moveToFirst();

		if (c.getInt(0) > 0) {
			database.update(context.getString(R.string.profilepicture_table_user), vals, context.getString(R.string.profilepicture_where_userid) + userId, null);
		} else {
			database.insert(context.getString(R.string.profilepicture_table_user), null, vals);
		}
	}

	@Override
	public void requestFailed(Exception e, Object context) {

	}

	public void setProfilePictureOfUser(int userId, String pic) {
		updateOrInsertData(getWritableDatabase(), pic, "now()", userId);
	}
}
